package servlets;

import db.MaintenanceDAO;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/ApproveMaintenanceServlet")
public class ApproveMaintenanceServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 检查用户是否登录
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("username") == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        // 检查用户角色是否有审批权限
        String role = (String) session.getAttribute("role");
        if (!"finance".equals(role) ) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "您没有权限执行此操作");
            return;
        }

        // 获取当前登录用户名作为审核人
        String reviewer = (String) session.getAttribute("username");

        int maintenanceId = Integer.parseInt(request.getParameter("id"));
        String action = request.getParameter("action");
        String newStatus = "approve".equals(action) ? "已通过" : "未通过";

        MaintenanceDAO dao = new MaintenanceDAO();
        try {
            boolean success = dao.updateMaintenanceStatus(maintenanceId, newStatus, reviewer);
            if (success) {
                response.sendRedirect("viewMaintenance.jsp?id=" + maintenanceId);
            } else {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "更新状态失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "数据库错误: " + e.getMessage());
        }
    }
}